import { ArgumentsHost, Catch, ExceptionFilter,HttpException,HttpStatus } from '@nestjs/common';
import * as moment from 'moment'

@Catch()
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp()
    const request = ctx.getRequest()
    const response = ctx.getResponse()

    const status = exception instanceof HttpException?
    exception.getStatus():
    HttpStatus.INTERNAL_SERVER_ERROR

    const message = exception.message

    const errorResponse = {
      status,
      message,
      code:1,
      path: request.url, // 错误的url地址
      method: request.method, // 请求方式
      timestamp: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'), // 错误的时间
    }

    response.status = status
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}
